package com.naughty.shopapi.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.UUID;

public class JWTUtil {
    private static final String SUBJECT = "edushopapi";

    private static final long EXPIRITION = 1000L * 60 * 60 * 36;
    private static final String APPSECRET_KEY = "edushopapi";

    /**
     * 生成token
     *
     * @param email
     * @return
     */
    public static String generateToken(String email) {
        String token = Jwts
                .builder()
                .setSubject(SUBJECT)
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .claim("email", email)
                .claim("role", email)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRITION))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256, APPSECRET_KEY)
                .compact();
        return token;
    }

    /**
     * 判断是否过期
     *
     * @param token
     * @return
     */
    public static boolean isExpiration(String token) {
        try {
            //解析token
            Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            return true;
        }
        return false;
    }

    /**
     * 刷新token
     *
     * @param email
     * @return
     */
    public static String refreshToken(String email) {
        final String token = JWTUtil.generateToken(email);
        return token;
    }
}
